import { useState, useRef, useEffect } from 'react';
import Webcam from 'react-webcam';
import { StatusBar } from './components/StatusBar';
import { CameraPreview } from './components/CameraPreview';
import { TemplateSelector } from './components/TemplateSelector';
import { BottomNav } from './components/BottomNav';
import { PermissionModal } from './components/PermissionModal';
import { PromotionPage } from './components/PromotionPage';
import { ProfilePage } from './components/ProfilePage';
import { motion, AnimatePresence } from 'framer-motion';
import { Template } from './types';

// 使用在线图片作为临时替代，增加到 30 张模板
const templates: Template[] = Array.from({ length: 30 }, (_, i) => ({
  imageUrl: `https://picsum.photos/800/600?random=${i + 1}`,
  id: i + 1,
  name: `模板 ${i + 1}`
}));

function App() {
  const [currentPage, setCurrentPage] = useState<'home' | 'camera' | 'profile'>('camera');
  const [isCameraOn, setIsCameraOn] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(templates[0]);
  const [showPermissionModal, setShowPermissionModal] = useState(true);
  const [networkStatus, setNetworkStatus] = useState(true);
  const [printerStatus, setPrinterStatus] = useState(true);
  const [cameraStatus, setCameraStatus] = useState(false);
  const [capturedImage, setCapturedImage] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);

  const webcamRef = useRef<Webcam>(null);

  useEffect(() => {
    // 检查网络状态
    const checkNetwork = () => {
      setNetworkStatus(navigator.onLine);
    };
    window.addEventListener('online', checkNetwork);
    window.addEventListener('offline', checkNetwork);
    checkNetwork();

    // 模拟打印机状态检查
    const checkPrinter = () => {
      setPrinterStatus(Math.random() > 0.1);
    };
    const printerInterval = setInterval(checkPrinter, 5000);
    checkPrinter();

    // 检查摄像头状态
    const checkCameraStatus = () => {
      if (webcamRef.current?.stream) {
        setCameraStatus(true);
        setIsCameraOn(true);
        setShowPermissionModal(false);
      } else {
        setCameraStatus(false);
        setIsCameraOn(false);
      }
    };

    // 初始检查
    checkCameraStatus();

    // 监听摄像头流的变化
    const webcamElement = webcamRef.current;
    if (webcamElement) {
      webcamElement.video?.addEventListener('loadedmetadata', checkCameraStatus);
    }

    return () => {
      window.removeEventListener('online', checkNetwork);
      window.removeEventListener('offline', checkNetwork);
      clearInterval(printerInterval);
      if (webcamElement) {
        webcamElement.video?.removeEventListener('loadedmetadata', checkCameraStatus);
      }
    };
  }, []);

  const handleCapture = async (imageData: string) => {
    if (!isProcessing) {
      try {
        setIsProcessing(true);
        setCapturedImage(imageData);
        
        // 创建合成图片
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (ctx && selectedTemplate) {
          // 设置画布大小为摄像头分辨率
          canvas.width = 1920;
          canvas.height = 1080;

          // 加载模板图片
          const templateImg = new Image();
          templateImg.src = selectedTemplate.imageUrl;
          await new Promise((resolve) => {
            templateImg.onload = resolve;
          });

          // 加载拍摄的图片
          const capturedImg = new Image();
          capturedImg.src = imageData;
          await new Promise((resolve) => {
            capturedImg.onload = resolve;
          });

          // 绘制拍摄的图片
          ctx.drawImage(capturedImg, 0, 0, canvas.width, canvas.height);
          
          // 绘制模板
          ctx.globalAlpha = 0.7;
          ctx.drawImage(templateImg, 0, 0, canvas.width, canvas.height);
          ctx.globalAlpha = 1.0;

          // 转换为图片数据
          const finalImage = canvas.toDataURL('image/jpeg', 0.9);

          // 保存图片
          const link = document.createElement('a');
          link.download = `photo_${new Date().getTime()}.jpg`;
          link.href = finalImage;
          link.click();

          // 如果打印机就绪，发送打印请求
          if (printerStatus) {
            // TODO: 实现打印功能
            console.log('Sending to printer:', finalImage);
          }

          // 显示成功提示
          alert('照片已保存！');
        }
      } catch (error) {
        console.error('Error processing image:', error);
        alert('处理图片时出错，请重试');
      } finally {
        setIsProcessing(false);
        setCapturedImage(null);
      }
    }
  };

  const handleTemplateSelect = (template: Template) => {
    setSelectedTemplate(template);
  };

  const handleCameraPermission = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      if (stream) {
        setIsCameraOn(true);
        setCameraStatus(true);
        setShowPermissionModal(false);
      }
    } catch (error) {
      console.error('Error accessing camera:', error);
      setCameraStatus(false);
      setIsCameraOn(false);
      setShowPermissionModal(true);
    }
  };

  const handleCameraDeny = () => {
    setShowPermissionModal(false);
    setCameraStatus(false);
    setIsCameraOn(false);
  };

  const renderPage = () => {
    switch (currentPage) {
      case 'home':
        return <PromotionPage />;
      case 'camera':
        return (
          <div className="flex flex-col h-[calc(100vh-4rem)]">
            {/* 摄像头预览区域 - 调整为 3/5 高度 */}
            <div className="h-[60vh] relative">
              <CameraPreview
                selectedTemplate={selectedTemplate}
                onCapture={handleCapture}
              />
            </div>

            {/* 模板选择区域 - 调整为 2/5 高度 */}
            <div className="h-[40vh] bg-white/90 backdrop-blur-sm rounded-t-2xl shadow-lg">
              <TemplateSelector
                templates={templates}
                selectedTemplate={selectedTemplate}
                onSelectTemplate={handleTemplateSelect}
              />
            </div>
          </div>
        );
      case 'profile':
        return <ProfilePage />;
    }
  };

  return (
    <div className="min-h-screen gradient-bg">
      <StatusBar
        networkStatus={networkStatus}
        printerStatus={printerStatus}
        cameraStatus={cameraStatus}
      />
      
      <div className="h-[calc(100vh-4rem)] overflow-y-auto">
        <main className="min-h-full pb-20">
          <AnimatePresence mode="wait">
            <motion.div
              key={currentPage}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.3 }}
              className="min-h-full"
            >
              {renderPage()}
            </motion.div>
          </AnimatePresence>
        </main>
      </div>

      <div className="fixed bottom-0 left-0 right-0 z-50">
        <BottomNav
          currentPage={currentPage}
          onPageChange={setCurrentPage}
        />
      </div>

      <PermissionModal
        visible={showPermissionModal}
        onGrant={handleCameraPermission}
        onDeny={handleCameraDeny}
      />
    </div>
  );
}

export default App; 